<?php

namespace app\api\controller;

use app\admin\model\Batch;
use app\admin\model\Customer;
use app\admin\model\Group;
use app\admin\model\m\Info;
use app\admin\model\Material;
use app\admin\model\Mcategory;
use app\admin\model\Pinxi;
use app\admin\model\Saler;
use app\common\controller\Api;
use app\admin\model\Admin;
use think\Db;
use think\Session;

//use app\common\library\Ems;
//use app\common\library\Sms;
//use fast\Random;
//use think\Config;
//use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    // todo   可能需要补充的一些方法:  'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'
    //protected $noNeedLogin = ['login', 'logout','captchaImage'];
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        //  TODO   api 接口安全:  无token或token不正确, 则不返回数据

        parent::_initialize();
    }

    /**
     * 厂区组别批次,
     * 分组以便联动查询, 按数据权限查询
     * @return data
     */
    public function fgdata(){
        $admin_id = intval($this->auth->id);
        $group = new Group();
        $batch = new Batch();
        $admin = Db::name("admin")->field("id,password,salt,token", true)->find($admin_id);
        // TODO  此处为临时方案,  权限角色需要固定
        $admin_role = Db::name("auth_group_access")->where("uid", $admin_id)->where("group_id","in", "6,7,9,10")->find();
        $is_manager = $admin_role ? true : false;
//echo Db::getLastSql(); print_r($is_manager);die;
        // TODO  关联relate表, 只查询所负责的组别,不重复

        $data['group'] = $group->alias("a")
            ->join("batchrelate b", "b.group_id=a.id", 'LEFT')
            ->where("a.status",'normal')
            ->where("a.factory_id", $admin['factory_id'])
            ->where("b.admin_id", $admin_id)
            ->field("a.id as value, a.name as text")
            ->order(['a.weigh'=>'desc','a.createtime'=>'desc'])
            ->group("a.id")
            ->select();
        //echo Db::getLastSql(); print_r($data);die;
        // 批次出栏1月后自动关闭，在前端数据填报界面不可选择，后台数据保留且可查看/导出
        //  定时任务暂无,
        //  TODO

        //组别对应批次
        $batchs = array_column($data['group'], null, "value");
        foreach($batchs as &$item){
            //  有管理类权限, 可以都看到组合批次.
            //  负责人只能看自己负责批次
            //  todo 131   个别情况下, 批次也可以显示, 如统计,经理级别查看;   或另外写一个接口
            if( $is_manager ) {
                $item['child'] = $batch->alias("a")
                    ->where("a.status", 'normal')
                    ->where("a.group_id", $item['value'])
                    ->field("a.id, a.id as value, a.name as text, a.pinxi_id")
                    ->with("batchrelate")
                    ->with("pinxi")
                    ->with("batchschedule")
                    ->order(['a.weigh' => 'desc', 'a.createtime' => 'desc'])
                    ->select();
            }
            else{
                //  批次, 或负责人状态修改后,  不可见批次
//                $item['child'] = $batch->alias("a")
//                    ->join("batchrelate b", "b.batch_id=a.id", 'LEFT')
//                    ->join("pinxi p", "p.id=a.pinxi_id", 'LEFT')
//                    ->where("a.status", 'normal')
//                    ->where("a.group_id", $item['value'])
//                    ->where("b.admin_id", $admin_id)
//                    ->where("a.status", 'normal')
//                    ->where("b.status", 'normal')
//                    ->field("a.id as value, CONCAT( '(' , p.name, ') ' , a.name) as text, b.admin_id, a.pinxi_id, p.name, b.status")
//                    ->with("batchschedule")
//                    ->order(['a.weigh' => 'desc', 'a.createtime' => 'desc'])
//                    ->select();
                $item['child'] = $batch->alias("a")
                    ->where("a.status", 'normal')
                    ->where("a.group_id", $item['value'])
                    //->where("b.admin_id", $admin_id)
                    ->field("a.id, a.id as value, a.name as text, a.pinxi_id")
                    ->with("batchrelate")
                    ->with("pinxi")
                    ->with("batchschedule")
                    ->order(['a.weigh' => 'desc', 'a.createtime' => 'desc'])
                    ->select();
            }
            #转换为显示数据
            $resArr = $item['child'] ;
            foreach( $resArr as &$vs){
                $vs['text'] = $vs['pinxi'] ? $vs['text'] . " (" . $vs['pinxi']['daici'] . $vs['pinxi']['name'] . ")" : "" ;
            }
            $item['child'] = $resArr ;
        }
        $data['batch']= $batchs;
        $data['admin']= $admin;

        // 种兔:   曾祖代厂-后备兔库(x厂)      或+  自己厂-后备兔库
        //$batch_zhongtu = Batch::getFactBatchStock(3, 5);
        $batch_zhongtu = Batch::getFactBatchStockV2($this->auth->factory_id, 5);
        $batch_zhongtu1 = [];
        #$batch_zhongtu1 =  Batch::getFactBatchStock( $this->auth->factory_id, 5);      // 自己厂区的后备兔库, 如需要,打开注释即可
        // 去除无库存
        foreach($batch_zhongtu as $k=> $val){
            if( intval($val['stock_num']) <= 0 ){
                unset($batch_zhongtu[$k]);
            }
        }
        $batch_zhongtu = array_merge($batch_zhongtu, $batch_zhongtu1);   // 刷新key从0开始
        $data['zhongtu'] = $batch_zhongtu;
//print_r($batch_zhongtu1);die;

        ## 后备库,品系,
        $houbei = Db::name("storepro")
            ->where("factory_id", $this->auth->factory_id)
            ->where("storea_id", 5)
            ->where("field2","gt", 0)
            ->field("field2 as text, field2 as value, sum(cal_num) as sum_num ")
            ->group("field2")
            ->select();
//        echo Db::getLastSql();die;
        $pinxiList = pinxi::getList();
        foreach ($houbei as &$val){
            $val['text'] = isset($pinxiList[$val['text']]) ? $pinxiList[$val['text']] : "";
        }
        $data['houbei'] = $houbei;

        ##  库位
        $storea = Db::name("storea")
            //->where("id", "in", [2,3,4] )
            ->field("id as value, name as text")
            ->select();
        // foreach($storea as &$val){}

        $data['storea'] = $storea;

        if(empty($data['group'])){
            $this->success('组别获取失败!请联系管理员', [], 402);
        }
        $this->success('成功', $data);

    }

    /**
     * 厂区组别批次  --  包括隐藏和删除的
     */
    public function allfgdata(){
        $admin_id = intval($this->auth->id);
        $group = new Group();
        $batch = new Batch();
        $admin = Db::name("admin")->field("id,password,salt,token", true)->find($admin_id);
        // TODO  此处为临时方案,  权限角色需要固定
        $admin_role = Db::name("auth_group_access")->where("uid", $admin_id)->where("group_id","in", "6,7,9,10")->find();
        $is_manager = $admin_role ? true : false;
//echo Db::getLastSql(); print_r($is_manager);die;
        $data['group'] = $group
            ->where("status",'normal')
            ->where("factory_id", $admin['factory_id'])
            ->field("id as value, name as text")
            ->order(['weigh'=>'desc','createtime'=>'desc'])
            ->select();

        //组别对应批次
        //  包括不用的批次
        $batchs = array_column($data['group'], null, "value");
        foreach($batchs as &$item){
            $item['child'] = $batch->alias("a")
                ->join("batchrelate b", "b.batch_id=a.id", 'LEFT')
                ->join("pinxi p", "p.id=a.pinxi_id", 'LEFT')
                //->where("a.status", 'normal')
                ->where("a.group_id", $item['value'])
                ->field("a.id as value, a.name as text, b.admin_id, a.pinxi_id, p.name, a.status, b.status as status_b ")
                ->order(['a.weigh' => 'desc', 'a.createtime' => 'desc'])
                ->select();
        }
        $data['batch']= $batchs;
        $data['admin']= $admin;

        if(empty($data['group'])){
            $this->success('组别获取失败!请联系管理员', [], 402);
        }
        $this->success('成功', $data);

    }

    /**
     * 获取x组别下的所有批次
     */
    public function btdata(){
        $admin_id = intval($this->auth->id);
        $factory_id = intval($this->auth->factory_id);
        $filter = $this->request->post();
        $batch = new Batch();

        $data['batch'] = $batch
            ->where("status","neq", 'deleted')
            ->where("factory_id", $factory_id ) // $admin['factory_id'])
            ->where("group_id", $filter['group_id'] )
            ->field("id as value, name as text")
            ->order(['weigh'=>'desc','createtime'=>'desc'])
            ->select();

        $this->success('成功', $data);
    }

    /**
     * 本厂区的销售员, 客户,
     */
    public function salerdata(){
        $admin_id = intval($this->auth->id);
        $factory_id = intval($this->auth->factory_id);
        $filter = $this->request->get();
        $saler = new Saler();
        $keyword = trim($filter['key']);
        $data['saler'] = $saler
            ->where("status","eq", "normal")
            ->where("factory_id", $factory_id )
            ->where("name", "LIKE", "%{$keyword}%" )
            ->where("deletetime", null )
            ->field("id as value, name as text")
            ->order(['weigh'=>'desc','createtime'=>'desc'])
            ->select();

        $this->success('成功', $data);
    }
    public function customerdata(){
        $admin_id = intval($this->auth->id);
        $factory_id = intval($this->auth->factory_id);
        $filter = $this->request->get();
        $customer = new Customer();
        $keyword = trim($filter['key']);
        $data['customer'] = $customer
            ->where("status","eq", "normal")
            ->where("factory_id", $factory_id )
            ->where("name", "LIKE", "%{$keyword}%" )
            ->where("deletetime", null )
            ->field("id as value, name as text")
            ->order(['weigh'=>'desc','createtime'=>'desc'])
            ->select();

        $this->success('成功', $data);
    }

    // 获取库位下, 品系的兔子及库存数量
    public function pinxidata(){
        $admin_id = intval($this->auth->id);
        $factory_id = intval($this->auth->factory_id);
        $filter = $this->request->get();
        $storea_id = trim($filter['storea_id']);

        $data['pinxi'] = Db::name("storepro")
            ->where("factory_id", $factory_id )
            ->where("storea_id", $storea_id )
            ->where("status","eq", "normal")
            ->where("deletetime", null )
            ->where("field2", "gt", 0 )
            ->field("field2 as value, field2 as text, sum(cal_num) as sum_num")
            ->order(['weigh'=>'desc','createtime'=>'desc'])
            ->group("field2")
            ->select();
        $pinxiList = Pinxi::getList();
        foreach($data['pinxi'] as &$val){
            $val['text'] = ( isset($pinxiList[$val['value']])? $pinxiList[$val['value']] : "" ) . " (库存: {$val['sum_num'] }) " ;
        }

        $this->success('成功', $data);
    }


    /**
     * 消毒剂二级联动
     * @return void
     */
    public function xdjdata(){
        $type = Db::name("disitype")
            ->where("status",1)
            ->field("id as value, name as text")
            ->order(['weigh'=>'desc','createtime'=>'desc'])
            ->select();
        $types = array_column($type, null, "value");

        // TODO  暂无 消毒剂名称  的表
        foreach($types as &$item){
            $item['child'] =  Db::name("disiname")
                ->where("status",1)
                ->where("disitype_id",$item['value'])
                ->field("id as value, name as text")
                ->order(['weigh'=>'desc','createtime'=>'desc'])
                ->select();

        }

        $data['type'] = $type;
        $data['xdj'] = $types;

        if(empty($data['type'])){
            $this->success('消毒剂类型获取失败!请联系管理员', [], 402);
        }
        $this->success('成功', $data);
    }

    /**
     * 厂区全部员工
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFactoryUser(){
        // TODO  优化一下 admin_id 与admin信息的查询
        $admin_id = intval($this->auth->id);
        $admin = Db::name("admin")->field("*")->find($admin_id);
        $data = Db::name('admin')->field("id as value, nickname as text, factory_id")->where("factory_id", $admin['factory_id'] )->select() ;
        $this->success('厂区全部员工', $data);
    }

    /**
     * 获取 X表单 的审批用户
     * @return void
     */
    public function getCheckUser(){
        $data=[];
        $this->success('审批用户', $data);
    }

    /**
     * 获取 X表单 的审批历史记录
     * @return void
     */
    public function getCheckList(){
        $data=[];
        $this->success('审批记录', $data);
    }

    /**
     *  TODO  重要功能!
     *  获取批次xx的 全部流程数据: 创建,加光,配种....
     *  为了让前端体现这个批次的全部流程
     *
     */
    public function batchProcess(){
        $data=[];


        $this->success('', $data);
    }

    /**
     * 用户的站内信
     * @return void
     */
    public function getMailbox(){
        $data['list'] =[];
//        $item = [
//            'title' => '系统通知',
//            'msg_text' => '您有1条新的审批需要处理',
//            'template' => ['id'=> 1, 'name'=> '销售单提醒' ],
//            'id' => 1233,
//            'createtime' => '2023-1-13 17:20:20',
//            'url' => '/pages/sale/list/index'
//        ];
//        $item1 = [
//            'title' => '预警信息!',
//            'msg_text' => '批次AB202221231 需要接产,请于7日内处理',
//            'template' => ['id'=> 2, 'name'=> '接产提醒' ],
//            'id' => 1233,
//            'createtime' => '2023-1-13 17:20:20',
//            'url' => '/pages/producelist/birth'
//        ];
//
//        array_push($data['list'], $item1) ;
//        array_push($data['list'], $item) ;
//        array_push($data['list'], $item) ;
//        array_push($data['list'], $item1) ;

        $this->success('', $data);
    }




    /**
     * 会员登录
     * http://test.tuzi.com/api/user/login?username=admin&password=admin123
     * http://test.tuzi.com/api/user/login?username=15909333333&password=123456
     * @ApiMethod (POST)
     * @param string $username 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password, 86400);
        if ($ret) {
            $aa = $this->auth->getUserInfo();
            $data = ['token' => $aa['token'], 'et'=> $aa ];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * http://test.tuzi.com/api/user/captchaImage
     * 是否开启验证码
     * @ApiMethod (GET)
     */
    public function captchaImage()
    {
        $res['captchaEnabled'] = false;
        $this->success('成功', $res);
    }

    /**
     * http://test.tuzi.com/api/user/getInfo
     * 获取账号信息
     * @ApiMethod (POST)
     */
    public function getInfo()
    {
        // @wtt   Api登录后，请求附带token,api识别token获取admin_id
        // echo $this->auth->id;
        $aa = Admin::get(intval($this->auth->id));
        if(!$aa){
            $this->success('登录已过期!', [], 401 );
        }
        $data = ['userinfo' => [
            'nickname' => $aa['nickname'],
            //'token' => $aa['token'],
            'updatetime' => $aa['updatetime'],
            'userName' => $aa['username'],
            'status' => $aa['status'],
            'email' => $aa['email'],
            'avatar' => $aa['avatar'],
            'name' => $aa['nickname'],
            'roles' => [],          //  todo
            'permissions' => [],    //  todo
        ]];
        $this->success('成功', $data);
    }

}

// todo
// 预留测试账号，给审核的，只给查询权限,  例如小程序审核，app审核
//
